import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getCookie, getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist
const noTokenList = ['/404','/401'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {

  //todo 刷新页面 store.getters.会被清空，需要重新调用接口获取。这里可以采取别的方式，例如使用localstory，但是vuex使用的是内存，效率上要高一些，这里更改，在每次刷新页面的时候，也就是某一个字段为空之后，调用接口，相当于刷新vuex的内存
  // console.log(store.getters.avatar)
  // console.log(store.getters.token)
  // console.log(store.getters.name)
  // console.log(store.getters.permissionRouters)

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (noTokenList.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next()
  }else if (hasToken) {
   if (to.path === '/login') {
     // if is logged in, redirect to the home page
     next({ path: '/' })
     NProgress.done()
   } else {
     if (store.getters.resourceFlag !== "1") {
       store.dispatch('user/getResource').then(accessRoutes => {
         router.addRoutes(accessRoutes); // 动态添加可访问路由表
         next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
       }).catch(err => {
         Message.error(err)
         next(`/login?redirect=${to.path}`)
         NProgress.done()
       })
     }else{
       const hasPermissions  = store.getters.permissionRouters;
       if (hasPermissions && hasPermissions.length < 1){
         next({ path: '/401' });
         await store.dispatch('user/logout')
         NProgress.done();
       } else  if (to.path === '/dashboard'){
         next()
         NProgress.done();
       } else if (hasPermissions.includes(to.path)) {
         next();
         NProgress.done();
       } else {
         next({ path: '/404' });
         NProgress.done();
       }
     }
   }
  } else {
     if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
